<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>文字转语音</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10px;
      padding-top: 20px;
    }

    button {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <textarea id="input" placeholder="hello word"></textarea>
  <button id="changeVoice">换一种声音</button>
  <button id="play">播放</button>
</body>
<script>
  "use strict"; {
    let play = document.getElementById("play")
    let input = document.getElementById("input")
    let changeVoice = document.getElementById("changeVoice")

    // 声源列表，可通过speechSynthesis对象，监听voiceschanged方法获取
    // 查看支持语言文本
    let voiceList = []
    speechSynthesis.addEventListener("voiceschanged", () => {
      voiceList = speechSynthesis.getVoices()
    })

    // 使用继承的方法来实现吧
    class Speaker extends SpeechSynthesisUtterance {
      constructor(text = "hello word", volume = 1, lang = "zh-CN") {
        super()

        // 设置播放的文本
        super.text = text
        // 播放的音量，默认为1，最高音量
        super.volume = volume
        // 语言类型
        super.lang = lang
      }
      play() {
        this.stop()
        // speak 方法是要传入 SpeechSynthesisUtterance 的对象才能播放的，
        // Speaker 中继承了该对象，故传入 this 即可
        speechSynthesis.speak(this)
      }
      stop() {
        // speechSynthesis: 表示语音合成器
        speechSynthesis.cancel()
      }
      // 设置文本
      setText(text = "") {
        if (!text) throw new Error("请输入文本内容")
        super.text = text
      }
      // 设置音量
      setVolume(volume = 1) {
        if (volume < 0 || volume > 1) return console.log("音量不能小于0或大于1")
        super.volume = volume
      }
      // 设置声源
      setVoice(voice) {
        super.voice = voice
      }
    }

    // 创建发音对象
    const Speak = new Speaker()

    // 默认使用第一种声音
    let index = 0
    changeVoice.addEventListener("click", () => {
      index++
      Speak.setVoice(voiceList[index])
    })

    input.addEventListener("blur", function () {
      let text = this.value.trim()
      if (!text) throw new Error("请输入文本内容")
      // 设置文本内容
      Speak.setText(text)
    })

    // 点击按钮改变播放声音
    play.addEventListener("click", () => {
      Speak.play()
    })
  };
</script>

</html>